package com.yzz.shopping.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * @Author : yangzuozhe
 * @Time : On 2022/3/3 9:49
 *
 * @Description : ShoppingSearchHistoryUtils
 */
class ShoppingSearchHistoryUtils {
    companion object {
        private const val SHOPPING_SEARCH_HISTORY = "SHOPPING_SEARCH_HISTORY"

        fun addNewInfo(newString: String): MutableList<String?>? {
            var list: MutableList<String?>? = getInfoList()
            if (list == null) {
                list = mutableListOf()
            }
            if (!list.contains(newString)) {
                list?.add(0, newString)
                if (list?.size > 20) {
                    list = list?.subList(0, 19)
                }
                val data = Gson().toJson(list)
                PreferenceUtil.put(SHOPPING_SEARCH_HISTORY, data)
            }
            return list
        }

        fun getInfoList(): MutableList<String?>? {
            val value = PreferenceUtil.getString(SHOPPING_SEARCH_HISTORY, null)
            return if (value != null) {
                val type = object : TypeToken<MutableList<String>>() {}.type
                Gson().fromJson(value, type)
            } else {
                null
            }
        }

        fun clearInfo() {
            PreferenceUtil.put(SHOPPING_SEARCH_HISTORY, null)
        }
    }
}